package ar.com.tallerdos.smartdinner.sync;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import ar.com.tallerdos.smartdinner.cocina.MainActivity;
import ar.com.tallerdos.smartdinner.cocina.R;
import ar.com.tallerdos.smartdinner.model.Agregado;
import ar.com.tallerdos.smartdinner.model.Mesa;
import ar.com.tallerdos.smartdinner.model.Product;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class Sincronizador extends AsyncTask<Void, Void, Void> {
	
//    	private static final String SERVER_URL = "http://192.168.0.51/prueba";
	static final String SERVER_URL = "http://10.0.2.2/cake_2_4_6";
	private static final String COCINA_SERVICE = "consultarCocina.php";
	private static final String MESA_SERVICE = "consultarCocinaMesas.php";
	private static final String AGREGADO_SERVICE = "consultarCocinaAgregados.php";
	private static boolean initialSync = false;
	private static boolean checkBackGround = false;
	private List<Agregado> agregados;
	
	ProgressDialog pdLoading;
	MainActivity activity;
		
	
	public Sincronizador(MainActivity mainActivity) {
		activity = mainActivity;
		if(!checkBackGround){
		    pdLoading = new ProgressDialog(mainActivity);
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// this method will be running on UI thread
		if(!checkBackGround){
		    pdLoading.setMessage("\tLoading...");
		    pdLoading.show();
		}
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		String productosJson = llamarWebService(SERVER_URL + "/" + COCINA_SERVICE);
		boolean repetido = false;
		int index;
		
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
		List<Product> productos =  gson.fromJson(productosJson, new TypeToken<List<Product>>(){}.getType());
		
		if (productos == null) {
		    return null;
		}
		
		//Validar datos obtenidos
		validarRetorno(productos);
		
		for(Product prd: productos){
			index = 0;
			for(Product prd2:MainActivity.getDoingProductsFiltros()){
				
				//if(prd2.getID() == prd.getID() && prd2.getProductID() == prd.getProductID() && prd2.getPedidoID() == prd.getPedidoID()){					
				if(prd2.getID().equals(prd.getID())){	
					//Se verifica que el plato no haya sido cancelado por el mozo	
					if((prd2.getEstado().equals("Pendiente") && (prd.getEstado().equals("Cancelado")))){
						MainActivity.getDoingProductsFiltros().get(index).setEstado(prd.getEstado());
						MainActivity.getDoingProductsFiltros().get(index).setCantidad(prd.getCantidad());
						MainActivity.getDoingProductsFiltros().get(index).setComentario(prd.getComentario());
					}
					
					if(prd2.getEstado().equals("Comenzado") || prd2.getEstado().equals("Pendiente")){

						MainActivity.getDoingProductsFiltros().get(index).setCantidad(prd.getCantidad());
						MainActivity.getDoingProductsFiltros().get(index).setComentario(prd.getComentario());
						MainActivity.getDoingProductsFiltros().get(index).setAgregadoDesc(prd.getAgregadoDesc());
					}
					
					repetido = true;
					break;
				}
				index += 1;
			}
			if(!repetido && (prd.getEstado().equals("Pendiente") || prd.getEstado().equals("Comenzado"))){
				MainActivity.getDoingProductsFiltros().add(new Product(prd.getID(),prd.getDescripcion(),prd.getFecha(),prd.getEstado(), prd.getCantidad(),prd));
			}
			repetido = false;
		}
		
		if(MainActivity.getItemSelected()!= null){
			MainActivity.checkStatus(MainActivity.getItemSelected().getTitle().toString());
		}
		else{
			MainActivity.setDoingProducts(MainActivity.getDoingProductsFiltros());
		}
		
		if(!productos.isEmpty()){
			initialSync = true;
		}
		
		checkMesas();
		
		buscarAgregados();
		
		return null;

	}
	
	private Void buscarAgregados(){
		
		String agregadosJson = llamarWebService(SERVER_URL + "/" + AGREGADO_SERVICE);
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
		agregados =  gson.fromJson(agregadosJson, new TypeToken<List<Agregado>>(){}.getType());
		
		if (agregados == null) {
			return null;
		}
		
		if(agregados.size() > 0 && MainActivity.getDoingProducts().size() >0){
			
			sortListAgregados();
			
			for(Product prd: MainActivity.getDoingProducts()){
				prd.setAgregadoDesc("");
				for(Agregado agregado: agregados){
					if(agregado.getPedido_detalle_di().equals(prd.getID())){
						if(!prd.getAgregadoDesc().equals("")){
							prd.setAgregadoDesc(prd.getAgregadoDesc() + " / " + agregado.getDescripcion());
						}
						else{
							prd.setAgregadoDesc(agregado.getDescripcion());
						}
					}
				}
			}
		}
		
		return null;
		
	}
	
	private void sortListAgregados(){

		Collections.sort(agregados, new Comparator<Agregado>() {
			public int compare(Agregado emp1, Agregado emp2) {
				return emp1.getId()-emp2.getId();
			}
		});
	}

	private void checkMesas(){
		String mesasJson = llamarWebService(SERVER_URL + "/" + MESA_SERVICE);
		
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
		List<Mesa> mesas =  gson.fromJson(mesasJson, new TypeToken<List<Mesa>>(){}.getType());
		
		if (mesas != null) {
		    for(Product prd: MainActivity.getDoingProductsFiltros()){
		    	for(Mesa mesa: mesas){
		    			if(mesa.getPedidoId() == prd.getPedidoID() && !prd.getMesaID().contains(mesa.getMesaId().toString() + " y ") && !prd.getMesaID().contains(" y " + mesa.getMesaId().toString()) && !prd.getMesaID().equals(mesa.getMesaId().toString())){
		    				prd.setMesaID(prd.getMesaID() + " y " + mesa.getMesaId().toString());
		    			}
		    	}
		    }
		}
	}
	
	private void validarRetorno(List<Product> productos ) {
		
		//Se agrega un registro de espera
		boolean vacio = true;
		for(Product prd: productos){
			if(prd.getEstado().equals("Pendiente") || prd.getEstado().equals("Comenzado")){
				vacio = false;
				break;
			}
		}
		
		if( vacio && MainActivity.getDoingProductsFiltros().size() == 0){
			
			String currentDateTimeString = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
			
			MainActivity.getDoingProductsFiltros().add(new Product(-1,"Sin pedidos",currentDateTimeString,R.drawable.ic_sinpedidos,"Pendiente",0));
		}
		else{
			if(MainActivity.getDoingProductsFiltros().size() == 1 && !vacio){
				if(MainActivity.getDoingProductsFiltros().get(0).getID()== -1){
					MainActivity.getDoingProductsFiltros().clear();
				}
			}
		}
	}

	@Override
	protected void onPostExecute(Void result) {
		// this method will be running on UI thread
		super.onPostExecute(result);
				
		MainActivity.sortList();
		MainActivity.getAdapter().notifyDataSetChanged();
				
		if(!checkBackGround){
			pdLoading.dismiss();
			
			if(MainActivity.getDoingProductsFiltros().size()==0){
				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
				dialogBuilder.setTitle("Aclaracion");
				dialogBuilder.setMessage("No se encontraron platos asignados a la Cocina. Por favor, espere unos instantes para que se realicen nuevos pedidos");
				dialogBuilder.setPositiveButton("Aceptar",new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,int which) {
																
							}

						});

				AlertDialog alertDialog = dialogBuilder.create();
				alertDialog.show();
			}
		} else if (pdLoading != null) {
			pdLoading.dismiss();
		    
		}
	}

	private String llamarWebService(String url) {
		InputStream is = null;

		try {
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("categoria",MainActivity.getModoEjecucion().toString()));
			
			String fechaActual = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
			nameValuePairs.add(new BasicNameValuePair("fechaActual",fechaActual.replaceAll(" ", "%20")));
			
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.HOUR_OF_DAY, -4);
			
			fechaActual = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
			nameValuePairs.add(new BasicNameValuePair("fechaPrevia",fechaActual.replaceAll(" ", "%20")));
			
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			Log.e("log_tag", "Conexion exitosa");
		} catch (Exception e) {
			Log.e("log_tag", "Error en conexion http" + e.toString());
		}

		return convertToString(is);
	}

	public String convertToString(InputStream is) {
		// convert response to string
		String result = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
			Log.e("log_tag",
					"Conversion Exitosa del resultado" + result.toString());
		} catch (Exception e) {
			Log.e("log_tag",
					"Error en conversion del resultado " + e.toString());
		}

		return result;
	}
	
	public static void setBackGroundCheck(){
		checkBackGround = true;
	}
	
	public static boolean getInitialSync(){
		return initialSync;
	}
}
